package com.cynteka.cyfoman.ui;

import org.apache.commons.chain.*;
import org.jdesktop.swingx.JXTreeTable;
import org.jdesktop.swingx.treetable.TreeTableModel;

import javax.swing.*;
import javax.swing.table.TableModel;
import java.awt.*;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * User: Sergey
 * Date: 03.08.11
 * Time: 3:09
 */
public class RefreshComponentListener implements IEventListener, Command {

    Logger logger = Logger.getLogger(RefreshComponentListener.class.getName());

    public List<Component> getComponents() {
        return components;
    }

    public void setComponents(List<Component> components) {
        this.components = components;
    }

    private List<Component> components;

    @Override
    public void handleEvent(IEvent event) {
        for (Component component : components) {
            if (component.isShowing()) {
                if (component instanceof JXTreeTable) {
                    JXTreeTable jxTreeTable = (JXTreeTable) component;
                    TreeTableModel treeTableModel = jxTreeTable.getTreeTableModel();
                    if (treeTableModel instanceof Reloadable) {
                        Reloadable reloadable = (Reloadable) treeTableModel;
                        reloadable.reload();
                    } else {
                        logger.log(Level.WARNING, "Cannot refresh tree model because it's not instance of Reoadable");
                    }
                } else if (component instanceof JTable) {
                    JTable table = (JTable) component;
                    TableModel tableModel = table.getModel();
                    if (tableModel instanceof Reloadable) {
                        Reloadable reloadable = (Reloadable) tableModel;
                        reloadable.reload();
                    } else {
                        logger.log(Level.WARNING, "Cannot refresh tree model because it's not instance of Reoadable");
                    }
                }
            }
        }
    }

    @Override
    public boolean execute(org.apache.commons.chain.Context context) throws Exception {
        handleEvent(null);
        return false;
    }
}
